
/// 检查浏览器是否支持ActiveX
function IsActiveXSupported() {
    var isSupported = false;

    if(window.ActiveXObject) {
        return true;
    }

    if("ActiveXObject" in window) {
        return true;
    }

    try {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        isSupported = true;
    } catch (e) {
        if (e.name === "TypeError" || e.name === "Error") {
            isSupported = true;
        }
    }

    return isSupported;
}

/// 获取OCX对象
function getOcxObject() {
	return document.getElementById("ocxPlayer");
}

/// 检测OCX是否可用
function detectOcxSetup() {
	return getOcxObject().object;
}



/// 显示日志
function showLog(text) {
	console.log(text)
	$('#msg-span').html(text);
}

/// 显示通知
function showNotification(text) {
	$('#msg-span').html(text);
}

/// 显示错误
function showError(text) {
	alert(text);
}

function msgbox(text) {
	alert(text);
}

var sliderTimer = 0;
var paused = false;

/// 初始化OCX
function initOcx() {
	var ocx = getOcxObject();

	ocx.BindEvent("OnPlayerEvent", function (event) {
		showLog('OnPlayerEvent. event: ' + event)

		if (nvs.EventType.MDECODE_EVENT_FORMAT_READY === event) {
			let duration = ocx.GetDuration() / 1000
			console.log('duration: ' + duration + ' s')
			$('#duration-span').html(duration)
		}
  });


  ocx.BindEvent("OnEndOfStream", function (reason) {
		 showLog('stream is end. reason: ' + reason)
	});

	/// 处理录像下载结束
	ocx.BindEvent("OnEndOfDownload", function (handle, reason) {
		showLog('download ' + handle + ' is end. reason: ' + reason)

		ocx.StopDownload(handle)
   });

	ocx.BindEvent("OnMouseEnter", function (x, y) {
		showLog('OnMouseEnter ' + x + ',' + y)
    });

	ocx.BindEvent("OnMouseLeave", function (x, y) {
		showLog('OnMouseLeave ' + x + ',' + y)
    });

	ocx.BindEvent("OnMouseButtonDown", function (x, y, which, modifier) {
		showLog('OnMouseButtonDown ' + x + ',' + y)
    });
	
}


function onBtnLogin() {
	var ocx = getOcxObject();
	if (nvs.IsLogin(ocx)) {
		nvs.Logout(ocx)
		onLogout()
	} else {
		var ip = $('#ip').val();
		var port = $('#port').val();
		port = parseInt(port)
		var name = $('#username').val();
		var password = $('#passwd').val().toString();
		
		console.log(ip + ':' + port)
		console.log(name + ':' + password)
		
		var ret = nvs.Login(ocx, ip, port, name, password)
		console.log(ret)
		if (ret) {
			onLoginSuccess();
		} else {
			onLoginFailed();
		}
	}
}

function onLoginSuccess() {
	$('#video-frame').show();
	$('#btn-login').html('登出');
}

function onLoginFailed() {
	var ocx = getOcxObject();
	var text = "login failed"
	$('.validate-tip').html(text).show();
}

function onLogout() {
	$('#btn-login').html('登录');
}



function onBtnOpenFile () {
	var ocx = getOcxObject();
	var filepath = $('#input-filepath').val();

	showLog('open file: ' + filepath)

	nvs.OpenFile(ocx, filepath)
	nvs.Play(ocx)
	paused = false;

	sliderTimer = setInterval(function () {
		let pos = nvs.GetTime(ocx) / 1000
		let percent = nvs.GetPos(ocx) * 100
		$('#time-span').html(pos);
		$('#slider').slider( "value", percent );
	}, 1000);
}

function onBtnPlay () {
	var ocx = getOcxObject();
	nvs.Play(ocx)
	paused = false
}

function onBtnStop () {
	var ocx = getOcxObject();
	nvs.Stop(ocx)

	clearInterval(sliderTimer);
	sliderTimer = 0;
	paused = false
}

function onBtnPause () {
	var ocx = getOcxObject();
	nvs.Pause(ocx, true)
	paused = true
}

function onBtnSlow () {
	var ocx = getOcxObject();
	var scale = 1/2.0
	nvs.SetScale(ocx, scale)
}

function onBtnFast () {
	var ocx = getOcxObject();
	var scale = 2.0
	nvs.SetScale(ocx, scale)
}

function onBtnSound () {
	var ocx = getOcxObject();
	nvs.CloseSound(ocx, true)
}

function onBtnSnap () {
	var ocx = getOcxObject();
	var filepath = "d:\snap.bmp"
	nvs.Snap(ocx, filepath)
}

function onBtnRatio () {
	var ocx = getOcxObject();
	nvs.SetRatio(ocx, -1, -1)
}

function onBtnTogglePlay () {
	var ocx = getOcxObject();

	paused = !paused;
	nvs.Pause(ocx, paused)
}


function onBtnOpenLive() {
	var ocx = getOcxObject();
	var devID = $('#input-device').val();
	var softversion = ocx.GetSoftVersion();

	showLog('open live: ' + devID + ':' + softversion)
	


	nvs.OpenLive(ocx, devID)
	nvs.Play(ocx)
}

function onBtnQueryRecord() {
	var ocx = getOcxObject();
	var devID = $('#input-record-device').val();
	var tmBegin = $('#start-datepicker').datepicker('getDate');
	var tmEnd = $('#stop-datepicker').datepicker('getDate');
	var beginSeconds = Math.round(tmBegin.getTime() / 1000);
	var endSeconds = Math.round(tmEnd.getTime() / 1000);
	console.log(beginSeconds)
	console.log(endSeconds)
	
	var recordJson = nvs.QueryRecord(ocx, devID, beginSeconds, endSeconds, 0, 0)
	var recordResult = eval("(" + recordJson + ")");
	var records = recordResult.items;
	console.log(recordResult)

	if (records.length > 0) {
		clearSearchFile();
		for (var i in records) {
			appendSearchFile(records[i]);
		}
		
		$('#result-file ul li').dblclick(onDblClickFile);
	} else {
		showError("没有搜索到录像!");
	}
}

function onDblClickFile(event) {
	var rec = $(event.currentTarget).data("record");
	var ocx = getOcxObject();
	console.log(rec)

	downloadRecord(rec)
}

var downloadHandle = 0;

function downloadRecord(record) {
	var ocx = getOcxObject();
	var filename = 'd:\\' + record.id + '_'  + record.beginTime + '.ps'
	var endTime = record.beginTime + 60 ;
	console.log('StartDownload. begin: ' + record.beginTime + ' end: ' + endTime)
	downloadHandle = nvs.StartDownload(ocx, filename, record.id, record.beginTime, endTime, 0, 0, "")
	if (downloadHandle == 0) {
		showError("无法下载指定的录像!");
	} else {
		console.log('download ' + downloadHandle + ' started.');
	}
}

function stopDownload() {
	var ocx = getOcxObject();
	if (downloadHandle != 0) {
		nvs.StopDownload(ocx, downloadHandle);
		downloadHandle = 0;
	}
}

function playbackRecord(record) {
	var ocx = getOcxObject();
	nvs.OpenRecord(ocx, record.id, record.beginTime, record.endTime, 0, 0, "")
	nvs.Play(ocx)
}

function onBtnStopRecord() {
	stopDownload()
}

function onBtnOpenRecord() {
	var ocx = getOcxObject();

	console.log('onBtnOpenRecord')

	var devID = $('#input-record-device').val();
	var tmBegin = parseInt($('#input-record-begin').val())
	var tmEnd = parseInt($('#input-record-end').val())

	nvs.OpenRecord(ocx, devID, tmBegin, tmEnd, 0, 0, "")
	nvs.Play(ocx)

	console.log('nvs.OpenRecord')
}


function onBtnEnableFace() {
	var ocx = getOcxObject();
	var enabled = $('#btn-open-face').attr('checked') === 'checked'

	nvs.EnableDrawTrack(ocx, enabled)

	console.log('-------- onBtnEnableFace end')
}









function getTime() {
	var now = new Date(),
	h =now.getHours(),
	m =now.getMinutes(),
	s =now.getSeconds(),
	ms =now.getMilliseconds();
	return (h+":"+m+":"+s+ " " +ms);
}


function getDateFromInputUI(selector) {
	var date = $(selector).datepicker("getDate");
	return date.valueOf() / 1000;
}


function getDateString(date) {
	return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
}

function getTimeString(date) {
	return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}

function formatCTime(t) {
	var date = new Date(t * 1000);
	return getDateString(date) + " " + getTimeString(date);
}



function onPtzBtnDown(event) {
	var cmd = $(event.target).data("command");
	controlPtz(cmd, nvs.PTZCommand.PTZ_CMD_START);
}

function onPtzBtnUp(event) {
	var cmd = $(event.target).data("command");
	cmd = cmd;
	controlPtz(cmd, nvs.PTZCommand.PTZ_CMD_STOP);
}

function controlPtz(cmd, data) {
	console.log('controlPtz. ' + cmd + ',' + data)
	var speed = $('#slider-ptz').slider("option", "value");
	var ocx = getOcxObject();
	var devID = $('#input-device').val();
	ocx.ControlPtz(devID, cmd, speed, data);
}


function onBtnDrawNone() {
	var ocx = getOcxObject();
	ocx.EnableDrawGraph(nvs.DrawGraphMode.kDrawNone);
}

function onBtnDrawRect() {
	var ocx = getOcxObject();
	ocx.EnableDrawGraph(nvs.DrawGraphMode.kDrawRect);
}

function onBtnDrawPolygon() {
	var ocx = getOcxObject();
	ocx.EnableDrawGraph(nvs.DrawGraphMode.kDrawPolygon);
}

function onBtnDrawClear() {
	var ocx = getOcxObject();
	ocx.SetDrawGraph("");
}

var currentDrawGraph = ''

function onBtnDrawGet() {
	var ocx = getOcxObject();
	currentDrawGraph = ocx.GetDrawGraph();
	console.log(currentDrawGraph)
}

function onBtnDrawSet() {
	var ocx = getOcxObject();
	ocx.SetDrawGraph(currentDrawGraph);
}


function clearSearchFile() {
	$('#result-file ul li').remove();
}

function appendSearchFile(rec) {
	var html = "<li><p>设备: " + rec.id + "</p>"
	+ "<p>开始: " + formatCTime(rec.beginTime) + "</p>"
	+ "<p>结束: " + formatCTime(rec.endTime) + "</p>"
	+ "<p>文件: " + rec.recordID + "(双击下载)</p></li>";

	$('#result-file ul').append(html);
	$('#result-file ul li:last-child').data("record", rec);
}


function demo() {
    var ocx = getOcxObject();

}

function onBtnTest() {
	var ocx = getOcxObject();
	
}

